package com.wushi.lenovo.asia5b.app_ui.other.dialog;

import android.support.v7.widget.ListPopupWindow;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.umeng_sdk.ThirdInfoModel;
import com.mvp.base.BaseAppCompatActivity;
import com.mvp.base.BaseDialog;
import com.mvp.base.model.ResultModel;
import com.mvp.common.GlobalValue;
import com.mvp.dagger.modules.NetworkModule;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_model.profile.CodeModel;
import com.wushi.lenovo.asia5b.app_model.profile.CountryModel;
import com.wushi.lenovo.asia5b.app_model.profile.ValidModel;
import com.wushi.lenovo.asia5b.app_push.PushHelper;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupListAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupWindowHelper;
import com.wushi.lenovo.asia5b.app_utils.helper.CrashHelper;
import com.wushi.lenovo.asia5b.app_widget.ErrorTextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

public class FacebookMobileDialog extends BaseDialog {


    @BindView(R.id.bt_dialog_ok)
    Button bt_dialog_ok;
    @BindView(R.id.ll_facebooknotice)
    LinearLayout ll_facebooknotice;
    @BindView(R.id.tv_facebook_areacode)
    TextView tv_facebook_areacode;
    @BindView(R.id.et_facebook_phone)
    EditText et_facebook_phone;
    @BindView(R.id.tv_facebook_mobile_error)
    ErrorTextView tv_facebook_mobile_error;
    @BindView(R.id.tv_facebook_email_error)
    ErrorTextView tv_facebook_email_error;
    @BindView(R.id.et_facebook_code)
    EditText et_facebook_code;
    @BindView(R.id.tv_facebook_getcode)
    TextView tv_facebook_getcode;
    @BindView(R.id.tv_facebook_error)
    ErrorTextView tv_facebook_error;
    @BindView(R.id.bt_facebook_continue)
    Button bt_facebook_continue;
    @BindView(R.id.ll_facebookmobile)
    LinearLayout ll_facebookmobile;
    @BindView(R.id.et_facebook_email)
    EditText et_facebook_email;
    @BindView(R.id.ll_facebooknotice_facebook)
    LinearLayout ll_facebooknotice_facebook;
    @BindView(R.id.ll_facebooknotice_wechat)
    LinearLayout ll_facebooknotice_wechat;
    private PopupListAdapter<CountryModel> popupListAdapter;
    private ListPopupWindow popupWindow;
    private final List<CountryModel> countryModelList;
    private final BaseAppCompatActivity activity;
    protected CompositeDisposable composite;
    private ApiService apiService;
    private final ThirdInfoModel infoModel;
    private final ThirdInfoModel.SHARE_MEDIA share_media;
    private Disposable intervalDisposable;

    public FacebookMobileDialog(BaseAppCompatActivity activity, List<CountryModel> countryModelList, ThirdInfoModel infoModel) {
        super(activity);
        if (countryModelList == null) {
            countryModelList = new ArrayList<>();
        }
        for (CountryModel countryModel : countryModelList) {
            countryModel.setName(countryModel.getCalling_code());
        }
        this.countryModelList = countryModelList;
        this.activity = activity;
        this.infoModel = infoModel;
        share_media = infoModel.getPlatform();
        composite = new CompositeDisposable();
        apiService = NetworkModule.getRetrofit().create(ApiService.class);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_facebook_mobile;
    }

    private void showViewById(View view) {
        ll_facebooknotice.setVisibility(view.getId() == R.id.ll_facebooknotice ? View.VISIBLE : View.GONE);
        ll_facebookmobile.setVisibility(view.getId() == R.id.ll_facebookmobile ? View.VISIBLE : View.GONE);
        if (view.getId() == R.id.ll_facebooknotice) {
            ll_facebooknotice_facebook.setVisibility(share_media == ThirdInfoModel.SHARE_MEDIA.FACEBOOK ? View.VISIBLE : View.GONE);
            ll_facebooknotice_wechat.setVisibility(share_media == ThirdInfoModel.SHARE_MEDIA.WEIXIN ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    protected void initView() {
        et_facebook_email.setVisibility(share_media == ThirdInfoModel.SHARE_MEDIA.WEIXIN ? View.VISIBLE : View.GONE);
        setCanceledOnTouchOutside(false);
        showViewById(ll_facebookmobile);
        initPopupWindow();
    }

    private void initPopupWindow() {
        popupListAdapter = new PopupListAdapter<>(getContext(), R.layout.item_popupitem_login_adapter, countryModelList);
        popupWindow = PopupWindowHelper.getListPopupWindow(getContext(), popupListAdapter
                , tv_facebook_areacode, ListPopupWindow.WRAP_CONTENT);
    }

    private void sendCode() {
        String phone = et_facebook_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            tv_facebook_error.setVisibility(View.VISIBLE);
            return;
        }
        CountryModel selectCountryModel = popupListAdapter.getSelectItem();
        if (selectCountryModel == null) {
            tv_facebook_error.setVisibility(View.VISIBLE);
            return;
        }
        Observable<ResultModel<CodeModel>> resultModelObservable = apiService.sendCodeForBindFacebook(phone, selectCountryModel.getCalling_code());
        if (share_media == ThirdInfoModel.SHARE_MEDIA.WEIXIN) {
            resultModelObservable = apiService.sendCodeForBindWechat(phone, selectCountryModel.getCalling_code());
        }
        Disposable subscribe = resultModelObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    if (activity != null) {
                        activity.showLoadingBar(null);
                    }
                })
                .doAfterTerminate(() -> {
                    if (activity != null) {
                        activity.dismissLoadingBar("");
                    }
                })
                .subscribe(codeModelResultModel -> {
                    if (codeModelResultModel.isSuccess()) {
                        ToastUtil.showToast(getString(R.string.otp_send_success));
                        interval();
                        CodeModel data = codeModelResultModel.getData();
                        if (data != null) {
                            String otp_code = data.getOTP_code();
                            et_facebook_code.setTag(otp_code);
                            if (GlobalValue.isDebug) {
                                et_facebook_code.setText(otp_code);
                            }
                        }
                    } else {
                        ToastUtil.showToast(codeModelResultModel.getMsg());
                    }

                }, throwable -> {
                    CrashHelper.postCatchedException(throwable);
                    throwable.printStackTrace();
                });
        composite.add(subscribe);

    }

    private void bindFacebookMobile() {
        boolean b = false;
        String phone = et_facebook_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            tv_facebook_error.setVisibility(View.VISIBLE);
            b = true;
        }
        String code = et_facebook_code.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            tv_facebook_error.setVisibility(View.VISIBLE);
            b = true;
        } else {
            Object tag = et_facebook_code.getTag();
            if (tag != null && tag instanceof String) {
                String tagCode = (String) tag;
                if (!TextUtils.equals(tagCode, code)) {
                    ToastUtil.showToast(getString(R.string.invalid_code));
                }
            }
        }
        if (b) {
            return;
        }
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("email", infoModel.getEmail());
        map.put("third_id", infoModel.getUid());
        map.put("type", infoModel.getPlatform() == ThirdInfoModel.SHARE_MEDIA.WEIXIN ? "wechat" : "facebook");
        map.put("app_register_id", PushHelper.getRegistrationId());
        map.put("app_os", "1");
        map.put("otp", code);
        map.put("mobile", phone);
        Disposable subscribe = apiService.bindFacebookMobile(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    if (activity != null) {
                        activity.showLoadingBar(null);
                    }
                })
                .doAfterTerminate(() -> {
                    if (activity != null) {
                        activity.dismissLoadingBar("");
                    }
                })
                .subscribe(resultModel -> {
                    if (resultModel.isSuccess()) {
                        showViewById(ll_facebooknotice);
                    } else {
                        ToastUtil.showToast(resultModel.getMsg());
                    }

                }, throwable -> {
                    CrashHelper.postCatchedException(throwable);
                    throwable.printStackTrace();
                });
        composite.add(subscribe);
    }

    private void bindWechatEmailAndMobile() {
        boolean b = false;
        String email = et_facebook_email.getText().toString().trim();
        if (TextUtils.isEmpty(email)) {
            tv_facebook_email_error.setVisibility(View.VISIBLE);
            b = true;
        }
        String phone = et_facebook_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            tv_facebook_error.setVisibility(View.VISIBLE);
            b = true;
        }
        String code = et_facebook_code.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            tv_facebook_error.setVisibility(View.VISIBLE);
            b = true;
        }
        if (b) {
            return;
        }
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("union_id", infoModel.getUid() + "");
        map.put("email", email);
        map.put("name", infoModel.getName());
        map.put("mobile", phone + "");
        map.put("otp", code + "");
        Disposable subscribe = apiService.bindWechatMobileAndEmail(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    if (activity != null) {
                        activity.showLoadingBar(null);
                    }
                })
                .doAfterTerminate(() -> {
                    if (activity != null) {
                        activity.dismissLoadingBar("");
                    }
                })
                .subscribe(resultModel -> {
                    if (resultModel.isSuccess()) {
                        showViewById(ll_facebooknotice);
                    } else {
                        ToastUtil.showToast(resultModel.getMsg());
                    }

                }, throwable -> {
                    CrashHelper.postCatchedException(throwable);
                    throwable.printStackTrace();
                });
        composite.add(subscribe);
    }

    private void checkEmail(String email) {
//        if (TextUtils.isEmpty(email) || !email.contains("@")) {
//            return;
//        }
//        Disposable subscribe = apiService.checkEmailByRegister(email)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(validModelResultModel -> {
//                    if (validModelResultModel.isSuccess()) {
//                        ValidModel validModel = validModelResultModel.getData();
//                        if (validModel != null && !validModel.isValid()) {
//                            tv_facebook_email_error.setVisibility(View.VISIBLE);
//                        }
//                    }
//                }, throwable -> {
//                    CrashHelper.postCatchedException(throwable);
//                });
//        composite.add(subscribe);
    }

    private void checkMobile() {
        String phone = et_facebook_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            return;
        }
        CountryModel selectCountryModel = popupListAdapter.getSelectItem();
        if (selectCountryModel == null) {
            return;
        }
        Disposable subscribe = apiService.checkMobileByRegister(phone, selectCountryModel.getId() + "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(validModelResultModel -> {
                    if (validModelResultModel.isSuccess()) {
                        ValidModel validModel = validModelResultModel.getData();
                        if (validModel != null && !validModel.isValid()) {
                            tv_facebook_mobile_error.setVisibility(View.VISIBLE);
                        }
                    }
                }, throwable -> {
                    CrashHelper.postCatchedException(throwable);
                });
        composite.add(subscribe);
    }

    private void intervalResult(long aLong) {
        Timber.d("--->>>>>>>>---aLong:" + aLong);
        if (aLong == 0) {
            tv_facebook_getcode.setEnabled(true);
            tv_facebook_getcode.setText(R.string.chongxinhuoquyanzhengma);
        } else {
            tv_facebook_getcode.setEnabled(false);
            tv_facebook_getcode.setText(aLong + "s");
        }
    }

    private void interval() {
        if (intervalDisposable != null) {
            composite.remove(composite);
            intervalDisposable.dispose();
        }
        intervalDisposable = Observable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        intervalResult(59 - aLong);
                    }
                }, throwable -> {
                    intervalResult(0);
                });
        composite.add(intervalDisposable);
    }


    @Override
    protected void initListener() {
        popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                popupListAdapter.setSelectPosition(position);
                CountryModel model = popupListAdapter.getSelectItem();
                if (model != null) {
                    tv_facebook_areacode.setText("+" + model.getCalling_code());
                }
            }
        });
//        et_facebook_email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (!hasFocus) {
//                    String email = et_facebook_email.getText().toString();
//                    checkEmail(email);
//                }
//            }
//        });
        if (share_media != ThirdInfoModel.SHARE_MEDIA.WEIXIN) {
            et_facebook_phone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        checkMobile();
                    }
                }
            });
        }
        tv_facebook_error.setBindEditText(et_facebook_code, et_facebook_phone, et_facebook_email);
        tv_facebook_mobile_error.setBindEditText(et_facebook_phone);
        tv_facebook_email_error.setBindEditText(et_facebook_email);
    }

    @OnClick({R.id.bt_dialog_ok, R.id.bt_facebook_continue, R.id.tv_facebook_areacode
            , R.id.tv_facebook_getcode})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_facebook_areacode:
                PopupWindowHelper.showPopupWindow(popupWindow);
                break;
            case R.id.bt_dialog_ok:
                dismiss();
                break;
            case R.id.bt_facebook_continue:
                if (share_media == ThirdInfoModel.SHARE_MEDIA.FACEBOOK) {
                    bindFacebookMobile();
                } else {
                    bindWechatEmailAndMobile();
                }
                break;
            case R.id.tv_facebook_getcode:
                et_facebook_code.setTag("");
                sendCode();
                break;
            default:
                break;
        }
    }

    @Override
    protected int getGravity() {
        return Gravity.CENTER;
    }
    @Override
    protected int getWidthStyle() {
        return getScreenWidth(0.8f);
    }
    @Override
    public void dismiss() {
        if (composite != null) {
            composite.dispose();
        }
        super.dismiss();
    }
}
